<?php
class App_Source_Users_Validator extends Mozg_Property_Validator
{
	protected function ValidateUserName($value)
	{
		if (strlen($value) < 4)
		{
			$this->SetErrorMessage('userName', Mozg_Lang::_('LOGIN_CANNOT_BE_LESS_THAN_%_CHARACHTERS', 4));
			return false;
		}

		if (!preg_match('/^[a-z_\-0-9.]+$/uis', $value))
        {
            $this->SetErrorMessage('userName', Mozg_Lang::_('LOGIN_CONTAIN_UNSUPPORTED_CHARACHTERS'));
            return false;
        }

        $user = Mozg_Mapper::Get('Users')->GetOne(array('userName' => $value));

        if ($user && ($this->GetData()->GetId() != $user->GetId()))
        {
            $this->SetErrorMessage('userName', Mozg_Lang::_('LOGIN_ALREADY_EXISTS'));
            return false;
        }

		return true;
	}

	protected function ValidateGroup($group)
	{
		$obj = $this->GetData();

		$thisUser = Mozg::User()->GetId() == $obj->GetId();
		if (($thisUser && (Mozg::User()->GetGroup()->GetId() != $group->GetId()))
			||
			(!$thisUser && !in_array($group->GetId(), Mozg::User()->GetAvailableGroups())))
        {
            $this->SetErrorMessage('groupsCustom', Mozg_Lang::_('CHOOSE_MAIN_GROUP'));
            $this->AddErrorField('groupsCustom');
            return false;
        }

        return true;
	}

	protected function ValidatePassword($value)
	{
		$obj = $this->GetData();
		if ($obj->GetId() && !strlen($value) && !strlen($obj->GetTestPassword()))
		{
			return true;
		}

		if (Mozg::Lib('Str')->Len($value) < 6)
		{
            $this->SetErrorMessage('password', Mozg_Lang::_('Password cannot be less then %s symbols', 6));
            return false;
		}

		if ($value != $obj->GetTestPassword())
		{
            $this->SetErrorMessage('password', Mozg_Lang::_('PASSWORDS_DO_NOT_MATCH'));
            $this->AddErrorField('testPassword');
            return false;
		}

		return true;
	}
}